﻿/// <reference path="/script/jsUtil.js"/> 
/// <reference path="/script/main.js"/> 
/// <reference path="/Js/ext-5.0.0-gpl/build/ext-all.js"/> 
/// <reference path="/Js/app.js"/>
/**
* 
*/
var myStore;
Ext.require('RBAC.Js.RBAC_Module');
Ext.onReady(function () {
    var IsChangeLoginStyle = RBAC.Js.RBAC_Module.SystemGetBool("House", "IsChangeLoginStyle");

    Ext.Loader.setConfig({ enabled: true, paths: {} });

    var departs = [];
    var _tree = [];
    var HardStr = siteTracker.q.HardStr;
    Fingerprint2.getV18({}, function (finger, components) {
        finger = hex_md5(finger);
        
        if (HardStr) {
            setTimeout(function () {
                $("#txtUserPass").attr("type", "password");
            }, 800);

            var d = (new Date()).getTime();
            var max = 99999; var min = 11111;
            var rand = Math.floor(Math.random() * (max - min + 1) + min);
            var checkstr = hex_md5(finger+";"+ HardStr + ";" + d + ";" + rand);

            var url =  "/Org/Services/Org_Hards.asmx/CheckHard";

            //检测安装
            CheckInstall(HardStr,d,rand, checkstr);

            $("form[name=fm]").submit(function () {
                return CheckLogin(checkstr, d, rand);
            });

        } else {
            $("#main").html("欢迎使用").fadeIn(500);
            return;
        }
   

    })
    function CheckLogin(CheckStr, Timestamp, rand) {
        $("input[type=submit]").prop("disable", true);
        if ((!$("#txtUserName").val()) ||
            $("#txtUserName").val() == "") {
            $.messager.alert("提示信息", "请选择部门和用户名！", "info");
            $("input[type=txtUserName]").prop("disable", false);
            return false;
        }

        if (!$("#txtUserPass").val()) {
            $.messager.alert("提示信息", "请输入密码！", "info");
            $("input[type=txtUserName]").prop("disable", false);
            $("#txtUserPass").focus();
            return false;
        }

        var result = "登陆成功，正在跳转到工作台。";

        $.messager.progress({ title: '提示信息', msg: '正在登陆' });
        var userId, userName;
        if (IsChangeLoginStyle) {
            userName = $("#txtUserName").val();
            userId = 0;
        } else {
            userId = $("#txtUserName").val();
            userName = '';
        }
        console.log(userId,userName);
        $.post("/RBAC/Services/RBAC_Users.asmx/CheckLogin", {
            UserId: userId,
            UserPass: hex_md5($("#txtUserPass").val()),
            HardStr: HardStr,
            CheckStr: CheckStr,
            UserName: userName,
            Timestamp: Timestamp,
            Rand:rand
        }, function (v) {
            $.messager.progress("close");
            switch ($(v).find("HardStr").text()) {
                case "Success":
                    location.href = "app.aspx";
                    break;
                case "UserErr":
                    result = "账号或密码错误！";
                    $("input[type=txtUserName]").prop("disable", false);
                    break;
                case "NoPermiss":
                    result = "没有设定角色，禁止登陆。";
                    $("input[type=txtUserName]").prop("disable", false);
                    break;
                default:
                    result = "系统未正确安装或密码错误！";
                    $("input[type=txtUserName]").prop("disable", false);
                    break;
            }
            $.messager.alert("提示信息", result, "info");
        });
        return false;
    }

    //检测是否已经安装
    function CheckInstall(HardStr,d,rand, CheckStr) {
        //与服务器通信
        $.messager.progress({ title: '提示信息', msg: '系统检测，请稍候...' });
        $.ajax({
            url: "/Org/Services/Org_Hards.asmx/CheckHard",
            data: {
                HardStr: HardStr,
                CheckStr: CheckStr,
                Ua: navigator.userAgent,
                Browser: navigator.appName,
                BrowserVersion: navigator.appVersion,
                Os: detectOS,
                ScreenWidth: window.screen.availWidth,
                ScreenHeight: window.screen.availHeight,
                notEndBranch: 1, Timestamp: d, Rand: rand
            },
            success: function (r) {
                //判断后台的登陆设置,IsChangeLoginStyle是true改变登录设置为手动输入，false为默认
                if (IsChangeLoginStyle) {
                    $("#main").removeAttr('style');
                    $("div").remove("#departs");
                }
                else {
                    var X_DEPARTS = {};
                    departs = $(r).find("NewDataSet").find("ds");

                    if (!departs.length) {
                        location.href = '/Org/Default.htm?HardStr=' + HardStr;
                        return;
                    }
                    departs.each(function (k, v) {
                        X_DEPARTS[$(v).find("DepartId").text()] = {
                            ParentId: $(v).find("ParentId").text(),
                            DepartId: $(v).find("DepartId").text(),
                            DepartName: $(v).find("DepartName").text()
                        };
                    });
                    if ($("#txtDepart").hasClass("xclass-org-departs")) {
                        var Tree = {};
                        for (var _depart in X_DEPARTS) {
                            var _temp = X_DEPARTS[_depart];
                            if (_temp.ParentId == 0) {
                                //把公司名称写到浏览器标题栏上
                                try {
                                    window.postMessage('win.title="{0}"'.format(_temp.DepartName), window.location);
                                } catch (e) { }
                                _tree.push({
                                    id: 'DepartId' + _temp.DepartId,
                                    'DepartId': _temp.DepartId,
                                    'DepartName': _temp.DepartName,
                                    'IsDelete': _temp.IsDelete,
                                    'IsVirtual': _temp.IsVirtual, leaf: false,
                                    iconCls: 'monitor', expanded: true,
                                    children: getChildren(_temp)
                                });
                            }
                        }
                        if (_tree.length == 0) {
                            $.messager.alert("提示", "没有部门或没有顶级部门。");
                            return;
                        }
                        Tree = { rows: _tree, total: _tree.length };
                        var newspan = $("<span></span>"); $("#txtDepart").attr("type", "hidden");
                        $("#txtDepart").after(newspan);
                        var treepicker = Ext.create('Js.TreePicker', {
                            displayField: 'DepartName', fieldLabel: '', forceSelection: true,
                            editable: false, renderTo: newspan[0],
                            minPickerWidth: 200, valueField: 'DepartId',
                            width: 294,
                            minPickerHeight: 200,
                            resizable: true, autoScroll: true,
                            store: Ext.create('Ext.data.TreeStore', {
                                fields: ['DepartId', 'DepartName'],
                                collapsible: true, rootVisible: true,
                                root: {
                                    children: Tree.rows[0].children, expanded: true, DepartName: '选择部门', DepartId: 0
                                }
                            }),
                            height: 36,
                            listeners: {
                                select: function (field, value) {
                                    myStore.removeAll();
                                    var _departid = 0;
                                    if (field.value == 'root')
                                        _departid = 1;
                                    else
                                        _departid = field.value.replace('DepartId', '');
                                    $("#txtDepart").val(_departid);
                                    myStore.load({ params: { start: 0, limit: 100, txtDeparts: _departid, isTree: 1 } });//, store: myStore });
                                }
                            }
                        });
                        //定义UserName下拉框
                        var url = "/RBAC/Services/RBAC_Users.asmx/GetLists";
                        var newspan_user = $("<span></span>"); $("#txtUserName").attr("type", "hidden");
                        $("#txtUserName").after(newspan_user);

                        myStore = new Ext.data.Store({
                            fields: ['UserId', 'UserName'],
                            pageSize: 1000, autoLoad: true,//第一次是否加载
                            autoDestroy: true, queryMode: 'local',
                            proxy: {
                                type: 'ajax', url: url, startParam: '{startParam}', limitParam: 'rows', headers: { "Content-Type": 'application/json' },
                                reader: { rootProperty: 'd.Table.rows', totalProperty: 'd.Total' }
                            }
                        });
                        var treepicker_user = new Ext.form.ComboBox({
                            displayField: 'UserName', forceSelection: false, triggerAction: 'all',
                            editable: false, renderTo: newspan_user[0], queryParam: 'UserName', queryMode: 'local',
                            minPickerWidth: 200, valueField: 'UserId',
                            width: 294,
                            minPickerHeight: 200,
                            resizable: true,
                            store: myStore,
                            height: 36, emptyText: '选择用户',
                            listeners: {
                                select: function (field, value) {
                                    $("#txtUserName").val(field.value);
                                }
                            }
                        });
                        $("#txtDepart").combotree('setValue', '1');
                    } else {
                        $.map(X_DEPARTS, function (item) {
                            $("#txtDepart").addOption(item.DepartName, item.DepartId);
                        });
                    }
                    function getChildren(node) {
                        var _children = [];
                        for (var _j in X_DEPARTS) {
                            var _temp = X_DEPARTS[_j];
                            if (_temp.ParentId == node.DepartId) {
                                _children.push({
                                    id: 'DepartId' + _temp.DepartId,
                                    'DepartId': _temp.DepartId,
                                    DepartName: _temp.DepartName,
                                    'IsVirtual': _temp.IsVirtual, leaf: false,
                                    iconCls: 'monitor', expanded: true,
                                    children: getChildren(_temp)
                                });
                            }
                        }
                        return _children;
                    }
                    $.messager.progress("close");
                    $("#main").fadeIn(500);
                }
            },
            error: function () {
                $.messager.alert("提示", '与服务器通信失败，请与管理员联系。');
            }
        });
        return true;
    }
    function detectOS() {
        var sUserAgent = navigator.userAgent;
        var isWin = (navigator.platform == "Win32") || (navigator.platform == "Windows");
        var isMac = (navigator.platform == "Mac68K") || (navigator.platform == "MacPPC") || (navigator.platform == "Macintosh") || (navigator.platform == "MacIntel");
        if (isMac) return "Mac";
        var isUnix = (navigator.platform == "X11") && !isWin && !isMac;
        if (isUnix) return "Unix";
        var isLinux = (String(navigator.platform).indexOf("Linux") > -1);
        if (isLinux) return "Linux";
        if (isWin) {
            var isWin2K = sUserAgent.indexOf("Windows NT 5.0") > -1 || sUserAgent.indexOf("Windows 2000") > -1;
            if (isWin2K) return "Win2000";
            var isWinXP = sUserAgent.indexOf("Windows NT 5.1") > -1 || sUserAgent.indexOf("Windows XP") > -1;
            if (isWinXP) return "WinXP";
            var isWin2003 = sUserAgent.indexOf("Windows NT 5.2") > -1 || sUserAgent.indexOf("Windows 2003") > -1;
            if (isWin2003) return "Win2003";
            var isWinVista = sUserAgent.indexOf("Windows NT 6.0") > -1 || sUserAgent.indexOf("Windows Vista") > -1;
            if (isWinVista) return "WinVista";
            var isWin7 = sUserAgent.indexOf("Windows NT 6.1") > -1 || sUserAgent.indexOf("Windows 7") > -1;
            if (isWin7) return "Win7";
        }
        return "other";
    }
    
    function loadFilter(data) {
        if (!data.d) {
            data.d = { Table: {} };
        }
        if (!data.d.Table) data.d.Table = {};
        if (data.d.Total)
            data.d.Table.total = data.d.Total;
        else
            data.d.Table.total = 0;
        if (!data.d.Table.rows) data.d.Table.rows = [];
        return data.d.Table;
    }
});